

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" href="/img/favicon.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="Cheney">
  <meta name="keywords" content="Coding">
  
    <meta name="description" content="Opencv是一个开源的的跨平台计算机视觉库，内部实现了图像处理和计算机视觉方面的很多通用算法，对于python而言，在引用opencv库的时候需要写为import cv2。其中，cv2是opencv的C++命名空间名称，使用它来表示调用的是C++开发的opencv的接口">
<meta property="og:type" content="article">
<meta property="og:title" content="基于OpenCv的人脸识别">
<meta property="og:url" content="https://cheney822.gitee.io/2021/06/21/%E5%9F%BA%E4%BA%8EOpenCv%E7%9A%84%E4%BA%BA%E8%84%B8%E8%AF%86%E5%88%AB%EF%BC%88Python%E5%AE%8C%E6%95%B4%E4%BB%A3%E7%A0%81%EF%BC%89/index.html">
<meta property="og:site_name" content="Cheney blog">
<meta property="og:description" content="Opencv是一个开源的的跨平台计算机视觉库，内部实现了图像处理和计算机视觉方面的很多通用算法，对于python而言，在引用opencv库的时候需要写为import cv2。其中，cv2是opencv的C++命名空间名称，使用它来表示调用的是C++开发的opencv的接口">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://imgbed.cheney.cc/picgo/20210622184054832-20220405210112194-20220405210127628.png">
<meta property="og:image" content="https://imgbed.cheney.cc/picgo/20210622184156714-20220405210127665.png">
<meta property="og:image" content="https://imgbed.cheney.cc/picgo/20210622184233123-20220405210127726.png">
<meta property="og:image" content="https://imgbed.cheney.cc/picgo/20210622184310674-20220405210127776.png">
<meta property="og:image" content="https://imgbed.cheney.cc/picgo/20210622184401375-20220405210127821.png">
<meta property="og:image" content="https://imgbed.cheney.cc/picgo/20210702213815631-20220405210127859.png">
<meta property="og:image" content="https://imgbed.cheney.cc/picgo/2021070221383573-20220405210127938.png">
<meta property="og:image" content="https://imgbed.cheney.cc/picgo/20210702213904483-20220405210127976.png">
<meta property="og:image" content="https://imgbed.cheney.cc/picgo/20210702213915241-20220405210128054.png">
<meta property="og:image" content="https://imgbed.cheney.cc/picgo/20210702213930210-20220405210128105.png">
<meta property="og:image" content="https://imgbed.cheney.cc/picgo/20210702213935524-20220405210128184.png">
<meta property="og:image" content="https://imgbed.cheney.cc/picgo/992a49478a0a42869b872971a13fc151-20220405210128220.gif">
<meta property="article:published_time" content="2021-06-21T00:22:00.000Z">
<meta property="article:modified_time" content="2022-04-05T13:14:30.979Z">
<meta property="article:author" content="Cheney">
<meta property="article:tag" content="Python">
<meta property="article:tag" content="OpenCv">
<meta property="article:tag" content="深度学习">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://imgbed.cheney.cc/picgo/20210622184054832-20220405210112194-20220405210127628.png">
  
  
  <title>基于OpenCv的人脸识别 - Cheney blog</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hint.css@2/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"cheney822.gitee.io","root":"/","version":"1.8.14","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":1},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.4.1"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>Cheney Blog</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('https://imgbed.cheney.cc/Blog_config/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="基于OpenCv的人脸识别">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2021-06-21 08:22" pubdate>
        2021年6月21日 早上
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      16k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      82 分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">基于OpenCv的人脸识别</h1>
            
            <div class="markdown-body">
              <blockquote>
<p>实验环境：python 3.6 + opencv-python 3.4.14.51<br>建议使用 anaconda配置相同环境</p>
</blockquote>
<h1 id="背景"><a href="#背景" class="headerlink" title="背景"></a>背景</h1><h2 id="人脸识别步骤"><a href="#人脸识别步骤" class="headerlink" title="人脸识别步骤"></a>人脸识别步骤</h2><img src="https://imgbed.cheney.cc/picgo/20210622184054832-20220405210112194-20220405210127628.png" srcset="/img/loading.gif" lazyload/>

<center> <img src="" srcset="/img/loading.gif" lazyload width="60%">
<center><b><font size ='3'>图1：人脸识别流程图</font></b></center></font>



<h3 id="人脸采集"><a href="#人脸采集" class="headerlink" title="人脸采集"></a>人脸采集</h3><p>采集人脸图片的方法多种多样，可以直接从网上下载数据集，可以从视频中提取图片，还可以从摄像头实时的采集图片。</p>
<h3 id="人脸检测方法"><a href="#人脸检测方法" class="headerlink" title="人脸检测方法"></a>人脸检测方法</h3><p>人脸检测在实际中主要用于人脸识别的预处理，即在图像中准确标定出人脸的位置和大小。人脸图像中包含的模式特征十分丰富，如直方图特征、颜色特征、模板特征、结构特征及Haar特征等。人脸检测就是把这其中有用的信息挑出来，并利用这些特征实现人脸检测。</p>
<h3 id="人脸图像预处理"><a href="#人脸图像预处理" class="headerlink" title="人脸图像预处理"></a>人脸图像预处理</h3><p>对于人脸的图像预处理是基于人脸检测结果，对图像进行处理并最终服务于特征提取的过程。系统获取的原始图像由于受到各种条件的限制和随机 干扰，往往不能直接使用，必须在图像处理的早期阶段对它进行灰度校正、噪声过滤等图像预处理。对于人脸图像而言，其预处理过程主要包括人脸图像的光线补 偿、灰度变换、直方图均衡化、归一化、几何校正、滤波以及锐化等。 </p>
<h3 id="人脸特征提取"><a href="#人脸特征提取" class="headerlink" title="人脸特征提取"></a>人脸特征提取</h3><p>人脸识别系统可使用的特征通常分为视觉特征、像素统计特征、人脸图像变换系数特征、人脸图像代数 特征等。人脸特征提取就是针对人脸的某些特征进行的。人脸特征提取，也称人脸表征，它是对人脸进行特征建模的过程。人脸特征提取的方法归纳起来分为两大 类：一种是基于知识的表征方法；另外一种是基于代数特征或统计学习的表征方法。</p>
<h3 id="匹配与识别"><a href="#匹配与识别" class="headerlink" title="匹配与识别"></a>匹配与识别</h3><p>提取的人脸图像的特征数据与数据库中存储的特征模板进行搜索匹配，通过设定一个阈值，当相似度超过这一阈值，则把匹配得到的结果输 出。人脸识别就是将待识别的人脸特征与已得到的人脸特征模板进行比较，根据相似程度对人脸的身份信息进行判断。这一过程又分为两类：一类是确认，是一对一 进行图像比较的过程，另一类是辨认，是一对多进行图像匹配对比的过程。</p>
<h2 id="关于OpenCv"><a href="#关于OpenCv" class="headerlink" title="关于OpenCv"></a>关于OpenCv</h2><p>Opencv是一个开源的的跨平台计算机视觉库，内部实现了图像处理和计算机视觉方面的很多通用算法，对于python而言，在引用opencv库的时候需要写为import cv2。其中，cv2是opencv的C++命名空间名称，使用它来表示调用的是C++开发的opencv的接口</p>
<p>目前人脸识别有很多较为成熟的方法，这里调用OpenCv库，而OpenCV又提供了三种人脸识别方法，分别是LBPH方法、EigenFishfaces方法、Fisherfaces方法。本文采用的是LBPH（Local Binary Patterns Histogram，局部二值模式直方图）方法。在OpenCV中，可以用函数cv2.face.LBPHFaceRecognizer_create()生成LBPH识别器实例模型，然后应用cv2.face_FaceRecognizer.train()函数完成训练，最后用cv2.face_FaceRecognizer.predict()函数完成人脸识别。</p>
<p>CascadeClassifier，是Opencv中做人脸检测的时候的一个级联分类器。并且既可以使用Haar，也可以使用LBP特征。其中Haar特征是一种反映图像的灰度变化的，像素分模块求差值的一种特征。它分为三类：边缘特征、线性特征、中心特征和对角线特征。</p>
<h1 id="程序设计"><a href="#程序设计" class="headerlink" title="程序设计"></a>程序设计</h1><h2 id="人脸识别算法："><a href="#人脸识别算法：" class="headerlink" title="人脸识别算法："></a>人脸识别算法：</h2><img src="https://imgbed.cheney.cc/picgo/20210622184156714-20220405210127665.png" srcset="/img/loading.gif" lazyload/>

<center> <img src="" srcset="/img/loading.gif" lazyload width="60%">
<center><b><font size ='3'>图2：人脸识别模块图</font></b></center></font>




<h3 id="1-准备工作"><a href="#1-准备工作" class="headerlink" title="1.准备工作"></a>1.准备工作</h3><img src="https://imgbed.cheney.cc/picgo/20210622184233123-20220405210127726.png" srcset="/img/loading.gif" lazyload/>

<center> <img src="" srcset="/img/loading.gif" lazyload width="60%">
<center><b><font size ='3'>图3：准备阶段</font></b></center></font>



<p>首先读取config文件，文件中第一行代表当前已经储存的人名个数，接下来每一行是二元组（id，name）即标签和对应的人名<br>读取结果存到以下两个全局变量中。</p>
<figure class="highlight python"><table><tr><td class="gutter"><div class="code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></div></td><td class="code"><pre><code class="hljs python">id_dict = &#123;&#125;  <span class="hljs-comment"># 字典里存的是id——name键值对</span><br>Total_face_num = <span class="hljs-number">999</span>  <span class="hljs-comment"># 已经被识别有用户名的人脸个数,</span><br></code></pre></td></tr></table></figure>

<p>def init():  # 将config文件内的信息读入到字典中</p>
<p>加载人脸检测分类器Haar，并准备好识别方法LBPH方法</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-comment"># 加载OpenCV人脸检测分类器Haar</span><br>face_cascade = cv2.CascadeClassifier(<span class="hljs-string">&quot;haarcascade_frontalface_default.xml&quot;</span>)<br><span class="hljs-comment"># 准备好识别方法LBPH方法</span><br>recognizer = cv2.face.LBPHFaceRecognizer_create()<br></code></pre></td></tr></table></figure>

<p>然后打开标号为0的摄像头</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs python">camera = cv2.VideoCapture(<span class="hljs-number">0</span>)  <span class="hljs-comment"># 摄像头</span><br>success, img = camera.read()  <span class="hljs-comment"># 从摄像头读取照片</span><br></code></pre></td></tr></table></figure>



<h3 id="2-录入新面容"><a href="#2-录入新面容" class="headerlink" title="2.录入新面容"></a>2.录入新面容</h3><img src="https://imgbed.cheney.cc/picgo/20210622184310674-20220405210127776.png" srcset="/img/loading.gif" lazyload/>

<center> <img src="" srcset="/img/loading.gif" lazyload width="60%">
<center><b><font size ='3'>图4：录入人脸</font></b></center></font>





<h4 id="2-1采集面容"><a href="#2-1采集面容" class="headerlink" title="2.1采集面容"></a>2.1采集面容</h4><p>创建文件夹data用于储存本次从摄像头采集到的照片，每次调用前先清空这个目录。</p>
<p>然后是一个循环，循环次数为需要采集的样本数，摄像头拍摄取样的数量,越多效果越好，但获取以及训练的越慢。</p>
<p>循环内调用<code>camera.read()</code>返回值赋给全局变量success,和img 用于在GUI中实时显示。</p>
<p>然后调用<code>cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)</code>用于将采集到的图片转为灰度图片减少计算量。</p>
<p>然后利用加载好的人脸分类器将每一帧摄像头记录的数据带入OpenCv中，让Classifier判断人脸。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-comment"># 其中gray为要检测的灰度图像，1.3为每次图像尺寸减小的比例，5为minNeighbors</span><br>faces = face_cascade.detectMultiScale(gray, <span class="hljs-number">1.3</span>, <span class="hljs-number">5</span>)<br></code></pre></td></tr></table></figure>

<p>faces为在img图像中检测到的人脸，然后利用cv2.rectangle在人脸一圈画个矩形。并把含有人脸的区域储存进入data文件夹<br>注意这里写入时，每个图片的标签时<code>Total_face_num</code>即当前共有多少个可识别用户（在录入之前加一），亦即当前用户的编号</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs python">cv2.rectangle(img, (x, y), (x + w, y + w), (<span class="hljs-number">255</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>))<br>cv2.imwrite(<span class="hljs-string">&quot;./data/User.&quot;</span> + <span class="hljs-built_in">str</span>(T) + <span class="hljs-string">&#x27;.&#x27;</span> + <span class="hljs-built_in">str</span>(sample_num) + <span class="hljs-string">&#x27;.jpg&#x27;</span>, gray[y:y + h, x:x + w])<br></code></pre></td></tr></table></figure>

<p>然后在循环末尾最后打印一个进度条，用于提示采集图像的进度<br>主要原理就是每次输出不换行并且将光标移动到当前行的开头，输出内容根据进度不断变化即可，同时在控件的提示框也输出进度信息</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;\r&quot;</span> + <span class="hljs-string">&quot;%&#123;:.1f&#125;&quot;</span>.<span class="hljs-built_in">format</span>(sample_num / pictur_num * <span class="hljs-number">100</span>) + <span class="hljs-string">&quot;=&quot;</span> * l + <span class="hljs-string">&quot;-&gt;&quot;</span> + <span class="hljs-string">&quot;_&quot;</span> * r, end=<span class="hljs-string">&quot;&quot;</span>)<br>var.<span class="hljs-built_in">set</span>(<span class="hljs-string">&quot;%&#123;:.1f&#125;&quot;</span>.<span class="hljs-built_in">format</span>(sample_num / pictur_num * <span class="hljs-number">100</span>))  <span class="hljs-comment"># 控件可视化进度信息</span><br>window.update()  <span class="hljs-comment"># 刷新控件以实时显示进度</span><br></code></pre></td></tr></table></figure>

<h4 id="2-2训练识别器"><a href="#2-2训练识别器" class="headerlink" title="2.2训练识别器"></a>2.2训练识别器</h4><p>读取data文件夹，读取照片内的信息，得到两个数组，一个faces存的是所有脸部信息、一个ids存的是faces内每一个脸部对应的标签，然后将这两个数组传给 <code>recog.train</code>用于训练</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-comment"># 训练模型  #将输入的所有图片转成四维数组</span><br>recog.train(faces, np.array(ids))<br></code></pre></td></tr></table></figure>


<p>训练完毕后保存训练得到的识别器到.yml文件中，文件名为人脸编号+.yml</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs python">recog.save(<span class="hljs-built_in">str</span>(Total_face_num) + <span class="hljs-string">&quot;.yml&quot;</span>)<br></code></pre></td></tr></table></figure>

<h4 id="2-3修改配置文件"><a href="#2-3修改配置文件" class="headerlink" title="2.3修改配置文件"></a>2.3修改配置文件</h4><p>每一次训练结束都要修改配置文件，具体要修改的地方是第一行和最后一行。<br>第一行有一个整数代表当前系统已经录入的人脸的总数，每次修改都加一。这里修改文件的方式是先读入内存，然后修改内存中的数据，最后写回文件。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs python">f = <span class="hljs-built_in">open</span>(<span class="hljs-string">&#x27;config.txt&#x27;</span>, <span class="hljs-string">&#x27;r+&#x27;</span>)<br>flist = f.readlines()<br>flist[<span class="hljs-number">0</span>] = <span class="hljs-built_in">str</span>(<span class="hljs-built_in">int</span>(flist[<span class="hljs-number">0</span>]) + <span class="hljs-number">1</span>) + <span class="hljs-string">&quot; \n&quot;</span><br>f.close()<br><br>f = <span class="hljs-built_in">open</span>(<span class="hljs-string">&#x27;config.txt&#x27;</span>, <span class="hljs-string">&#x27;w+&#x27;</span>)<br>f.writelines(flist)<br>f.close()<br><br></code></pre></td></tr></table></figure>

<p>还要在最后一行加入一个二元组用以标识用户。<br>格式为：标签+空格+用户名+空格，用户名默认为Userx（其中x标识用户编号）</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs python">f.write(<span class="hljs-built_in">str</span>(T) + <span class="hljs-string">&quot; User&quot;</span> + <span class="hljs-built_in">str</span>(T) + <span class="hljs-string">&quot; \n&quot;</span>)<br></code></pre></td></tr></table></figure>

<h3 id="3-人脸识别（刷脸）"><a href="#3-人脸识别（刷脸）" class="headerlink" title="3.人脸识别（刷脸）"></a>3.人脸识别（刷脸）</h3><img src="https://imgbed.cheney.cc/picgo/20210622184401375-20220405210127821.png" srcset="/img/loading.gif" lazyload/>

<center> <img src="" srcset="/img/loading.gif" lazyload width="60%">
<center><b><font size ='3'>图5：刷脸流程图</font></b></center></font>






<p>由于这里采用多个<code>.yml</code>文件来储存识别器（实际操作时储存在一个文件中识别出错所以采用这种方式），所以在识别时需要遍历所有的.yml文件，如果每一个都不能识别才得出无法识别的结果，相反只要有一个可以识别当前对象就返回可以识别的结果。而对于每一个文件都识别十次人脸，若成功五次以上则表示最终结果为可以识别，否则表示当前文件无法识别这个人脸。</p>
<p>识别过程中在GUI的控件中实时显示拍摄到的内容，并在人脸周围画一个矩形框，并根据识别器返回的结果实时显示在矩形框附近。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs python">idnum, confidence = recognizer.predict(gray[y:y + h, x:x + w])<br><span class="hljs-comment"># 加载一个字体用于输出识别对象的信息</span><br>font = cv2.FONT_HERSHEY_SIMPLEX<br><span class="hljs-comment"># 输出检验结果以及用户名</span><br>cv2.putText(img, <span class="hljs-built_in">str</span>(user_name), (x + <span class="hljs-number">5</span>, y - <span class="hljs-number">5</span>), font, <span class="hljs-number">1</span>, (<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">255</span>), <span class="hljs-number">1</span>)<br>cv2.putText(img, <span class="hljs-built_in">str</span>(confidence), (x + <span class="hljs-number">5</span>, y + h - <span class="hljs-number">5</span>), font, <span class="hljs-number">1</span>, (<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>), <span class="hljs-number">1</span>)<br></code></pre></td></tr></table></figure>





<h2 id="多线程："><a href="#多线程：" class="headerlink" title="多线程："></a>多线程：</h2><p>程序的两个功能之间可以独立运行，就需要采用多线程的方法，但当遇到临界资源的使用时，多个进程/线程之间就要互斥的访问以免出错，本程序中具体的设计方法：<br>本程序采用多线程的方法实现并行。<br>程序的三个按钮对应着三个功能，分别是录入人脸、人脸检测、退出程序。<br>由于程序中的用户界面是利用python中的tkinter库做的，其按钮的响应函数用command指出，所以这里在每个<code>command</code>跳转到的函数中设置多线程，每敲击一次就用<code>threading.Thread</code>创建一个新的线程，然后在新的线程的处理函数<code>target</code>中实现按钮原本对应的功能。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs python">p = threading.Thread(target=f_scan_face_thread)<br></code></pre></td></tr></table></figure>

<p>在涉及到摄像头的访问时，线程之间需要互斥的访问，所以设置了一个全局的变量<code>system_state_lock</code> 来表示当前系统的状态，用以实现带有优先级的互斥锁的功能。<br>锁状态为0表示摄像头未被使用，1表示正在刷脸，2表示正在录入新面容。<br>程序在实际执行的过程中如果状态为0，则无论是刷脸还是录入都能顺利执行，如果状态为1表示正在刷脸，如果此时敲击刷脸按钮则，系统会提示正在刷脸并拒绝新的请求，如果此时敲击录入面容按钮，由于录入面容优先级比刷脸高，所以原刷脸线程会被阻塞，</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">global</span> system_state_lock<br><span class="hljs-keyword">while</span> system_state_lock == <span class="hljs-number">2</span>:  <span class="hljs-comment"># 如果正在录入新面孔就阻塞</span><br>	  <span class="hljs-keyword">pass</span><br></code></pre></td></tr></table></figure>

<p>新的录入面容进程开始执行并修改系统状态为2，录入完成后状态变为原状态，被阻塞的刷脸进程继续执行，录入人脸线程刚执行完录入阶段现在正在训练，此时有两个线程并行，以此来保证训练数据的同时不影响系统的使用。</p>
<p>对于退出的功能，直接在函数内调用<code>exit()</code>，但是python的线程会默认等待子线程全部结束再退出，所以用<code>p.setDaemon(True)</code>将线程设置为守护线程，这样在主线程退出之后其它线程也都退出从而实现退出整个程序的功能。</p>
<h2 id="GUI设计："><a href="#GUI设计：" class="headerlink" title="GUI设计："></a>GUI设计：</h2><p>程序采用python中的tkinter库做可视化，优点是占用资源小、轻量化、方便。</p>
<ul>
<li>首先创建一个窗口命名为window然后设置其大小和标题等属性。</li>
<li>然后在界面上设定一个绿底的标签，类似于一个提示窗口的作用</li>
<li>然后分别创建三个按钮，并设置响应函数和提示字符，放置在window内部。</li>
<li>然后设置一个label类型的控件用于动态的展示摄像头的内容(将摄像头显示嵌入到控件中)。具体方法：创建video_loop()函数，在函数内访问全局的变量img，img是从摄像头读取到的图像数据。然后把img显示在label内。<br>使用window.after方法，在给定时间后调用函数一次，实现固定时间刷新控件，从而达到实时显示摄像头画面在GUI中的效果。</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs python">window.after(<span class="hljs-number">1</span>, video_loop)<br><span class="hljs-comment"># 这句的意思是一秒以后执行video_loop函数</span><br><span class="hljs-comment"># 因为这一句是写在video_loop函数中的所以每过一秒函数执行一次。</span><br></code></pre></td></tr></table></figure>

<h1 id="运行测试"><a href="#运行测试" class="headerlink" title="运行测试"></a>运行测试</h1><h2 id="说明"><a href="#说明" class="headerlink" title="说明"></a>说明</h2><p>测试环境：python 3.6 + opencv-python 3.4.14.51<br>需要的包：</p>
<p><img src="https://imgbed.cheney.cc/picgo/20210702213815631-20220405210127859.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<center> <img src="" srcset="/img/loading.gif" lazyload width="60%">
<center><b><font size ='3'>图6：需要的包</font></b></center></font>




<h2 id="录入人脸"><a href="#录入人脸" class="headerlink" title="录入人脸"></a>录入人脸</h2><p>从数据集录入</p>
<p><img src="https://imgbed.cheney.cc/picgo/2021070221383573-20220405210127938.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"><br>从摄像头录入<br><img src="https://imgbed.cheney.cc/picgo/20210702213904483-20220405210127976.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p><img src="https://imgbed.cheney.cc/picgo/20210702213915241-20220405210128054.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<h2 id="人脸识别"><a href="#人脸识别" class="headerlink" title="人脸识别"></a>人脸识别</h2><p><img src="https://imgbed.cheney.cc/picgo/20210702213930210-20220405210128105.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"><br><img src="https://imgbed.cheney.cc/picgo/20210702213935524-20220405210128184.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<h1 id="代码实现："><a href="#代码实现：" class="headerlink" title="代码实现："></a>代码实现：</h1><img src="https://imgbed.cheney.cc/picgo/992a49478a0a42869b872971a13fc151-20220405210128220.gif" srcset="/img/loading.gif" lazyload/>


<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br><span class="line">233</span><br><span class="line">234</span><br><span class="line">235</span><br><span class="line">236</span><br><span class="line">237</span><br><span class="line">238</span><br><span class="line">239</span><br><span class="line">240</span><br><span class="line">241</span><br><span class="line">242</span><br><span class="line">243</span><br><span class="line">244</span><br><span class="line">245</span><br><span class="line">246</span><br><span class="line">247</span><br><span class="line">248</span><br><span class="line">249</span><br><span class="line">250</span><br><span class="line">251</span><br><span class="line">252</span><br><span class="line">253</span><br><span class="line">254</span><br><span class="line">255</span><br><span class="line">256</span><br><span class="line">257</span><br><span class="line">258</span><br><span class="line">259</span><br><span class="line">260</span><br><span class="line">261</span><br><span class="line">262</span><br><span class="line">263</span><br><span class="line">264</span><br><span class="line">265</span><br><span class="line">266</span><br><span class="line">267</span><br><span class="line">268</span><br><span class="line">269</span><br><span class="line">270</span><br><span class="line">271</span><br><span class="line">272</span><br><span class="line">273</span><br><span class="line">274</span><br><span class="line">275</span><br><span class="line">276</span><br><span class="line">277</span><br><span class="line">278</span><br><span class="line">279</span><br><span class="line">280</span><br><span class="line">281</span><br><span class="line">282</span><br><span class="line">283</span><br><span class="line">284</span><br><span class="line">285</span><br><span class="line">286</span><br><span class="line">287</span><br><span class="line">288</span><br><span class="line">289</span><br><span class="line">290</span><br><span class="line">291</span><br><span class="line">292</span><br><span class="line">293</span><br><span class="line">294</span><br><span class="line">295</span><br><span class="line">296</span><br><span class="line">297</span><br><span class="line">298</span><br><span class="line">299</span><br><span class="line">300</span><br><span class="line">301</span><br><span class="line">302</span><br><span class="line">303</span><br><span class="line">304</span><br><span class="line">305</span><br><span class="line">306</span><br><span class="line">307</span><br><span class="line">308</span><br><span class="line">309</span><br><span class="line">310</span><br><span class="line">311</span><br><span class="line">312</span><br><span class="line">313</span><br><span class="line">314</span><br><span class="line">315</span><br><span class="line">316</span><br><span class="line">317</span><br><span class="line">318</span><br><span class="line">319</span><br><span class="line">320</span><br><span class="line">321</span><br><span class="line">322</span><br><span class="line">323</span><br><span class="line">324</span><br><span class="line">325</span><br><span class="line">326</span><br><span class="line">327</span><br><span class="line">328</span><br><span class="line">329</span><br><span class="line">330</span><br><span class="line">331</span><br><span class="line">332</span><br><span class="line">333</span><br><span class="line">334</span><br><span class="line">335</span><br><span class="line">336</span><br><span class="line">337</span><br><span class="line">338</span><br><span class="line">339</span><br><span class="line">340</span><br><span class="line">341</span><br><span class="line">342</span><br><span class="line">343</span><br><span class="line">344</span><br><span class="line">345</span><br><span class="line">346</span><br><span class="line">347</span><br><span class="line">348</span><br><span class="line">349</span><br><span class="line">350</span><br><span class="line">351</span><br><span class="line">352</span><br><span class="line">353</span><br><span class="line">354</span><br><span class="line">355</span><br><span class="line">356</span><br><span class="line">357</span><br><span class="line">358</span><br><span class="line">359</span><br><span class="line">360</span><br><span class="line">361</span><br><span class="line">362</span><br><span class="line">363</span><br><span class="line">364</span><br><span class="line">365</span><br><span class="line">366</span><br><span class="line">367</span><br><span class="line">368</span><br><span class="line">369</span><br><span class="line">370</span><br><span class="line">371</span><br><span class="line">372</span><br><span class="line">373</span><br><span class="line">374</span><br><span class="line">375</span><br><span class="line">376</span><br><span class="line">377</span><br><span class="line">378</span><br><span class="line">379</span><br><span class="line">380</span><br><span class="line">381</span><br><span class="line">382</span><br><span class="line">383</span><br><span class="line">384</span><br><span class="line">385</span><br><span class="line">386</span><br><span class="line">387</span><br><span class="line">388</span><br><span class="line">389</span><br><span class="line">390</span><br><span class="line">391</span><br><span class="line">392</span><br><span class="line">393</span><br><span class="line">394</span><br><span class="line">395</span><br><span class="line">396</span><br><span class="line">397</span><br><span class="line">398</span><br><span class="line">399</span><br><span class="line">400</span><br><span class="line">401</span><br><span class="line">402</span><br><span class="line">403</span><br><span class="line">404</span><br><span class="line">405</span><br><span class="line">406</span><br><span class="line">407</span><br><span class="line">408</span><br><span class="line">409</span><br><span class="line">410</span><br><span class="line">411</span><br><span class="line">412</span><br><span class="line">413</span><br><span class="line">414</span><br><span class="line">415</span><br><span class="line">416</span><br><span class="line">417</span><br><span class="line">418</span><br><span class="line">419</span><br><span class="line">420</span><br><span class="line">421</span><br><span class="line">422</span><br><span class="line">423</span><br><span class="line">424</span><br><span class="line">425</span><br><span class="line">426</span><br><span class="line">427</span><br><span class="line">428</span><br><span class="line">429</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-comment"># 实验环境：python 3.6 + opencv-python 3.4.14.51</span><br><br><span class="hljs-keyword">import</span> cv2<br><span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np<br><span class="hljs-keyword">import</span> os<br><span class="hljs-keyword">import</span> shutil<br><span class="hljs-keyword">import</span> threading<br><span class="hljs-keyword">import</span> tkinter <span class="hljs-keyword">as</span> tk<br><span class="hljs-keyword">from</span> PIL <span class="hljs-keyword">import</span> Image, ImageTk<br><br><span class="hljs-comment"># 首先读取config文件，第一行代表当前已经储存的人名个数，接下来每一行是（id，name）标签和对应的人名</span><br>id_dict = &#123;&#125;  <span class="hljs-comment"># 字典里存的是id——name键值对</span><br>Total_face_num = <span class="hljs-number">999</span>  <span class="hljs-comment"># 已经被识别有用户名的人脸个数,</span><br><br><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">init</span>():  <span class="hljs-comment"># 将config文件内的信息读入到字典中</span><br>    f = <span class="hljs-built_in">open</span>(<span class="hljs-string">&#x27;config.txt&#x27;</span>)<br>    <span class="hljs-keyword">global</span> Total_face_num<br>    Total_face_num = <span class="hljs-built_in">int</span>(f.readline())<br><br>    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-built_in">int</span>(Total_face_num)):<br>        line = f.readline()<br>        id_name = line.split(<span class="hljs-string">&#x27; &#x27;</span>)<br>        id_dict[<span class="hljs-built_in">int</span>(id_name[<span class="hljs-number">0</span>])] = id_name[<span class="hljs-number">1</span>]<br>    f.close()<br><br><br>init()<br><br><span class="hljs-comment"># 加载OpenCV人脸检测分类器Haar</span><br>face_cascade = cv2.CascadeClassifier(<span class="hljs-string">&quot;haarcascade_frontalface_default.xml&quot;</span>)<br><br><span class="hljs-comment"># 准备好识别方法LBPH方法</span><br>recognizer = cv2.face.LBPHFaceRecognizer_create()<br><br><span class="hljs-comment"># 打开标号为0的摄像头</span><br>camera = cv2.VideoCapture(<span class="hljs-number">0</span>)  <span class="hljs-comment"># 摄像头</span><br>success, img = camera.read()  <span class="hljs-comment"># 从摄像头读取照片</span><br>W_size = <span class="hljs-number">0.1</span> * camera.get(<span class="hljs-number">3</span>)<br>H_size = <span class="hljs-number">0.1</span> * camera.get(<span class="hljs-number">4</span>)<br><br>system_state_lock = <span class="hljs-number">0</span>  <span class="hljs-comment"># 标志系统状态的量 0表示无子线程在运行 1表示正在刷脸 2表示正在录入新面孔。</span><br><span class="hljs-comment"># 相当于mutex锁，用于线程同步</span><br><br><br><span class="hljs-string">&#x27;&#x27;&#x27;</span><br><span class="hljs-string">============================================================================================</span><br><span class="hljs-string">以上是初始化</span><br><span class="hljs-string">============================================================================================</span><br><span class="hljs-string">&#x27;&#x27;&#x27;</span><br><br><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">Get_new_face</span>():<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;正在从摄像头录入新人脸信息 \n&quot;</span>)<br><br>    <span class="hljs-comment"># 存在目录data就清空，不存在就创建，确保最后存在空的data目录</span><br>    filepath = <span class="hljs-string">&quot;data&quot;</span><br>    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> os.path.exists(filepath):<br>        os.mkdir(filepath)<br>    <span class="hljs-keyword">else</span>:<br>        shutil.rmtree(filepath)<br>        os.mkdir(filepath)<br><br>    sample_num = <span class="hljs-number">0</span>  <span class="hljs-comment"># 已经获得的样本数</span><br><br>    <span class="hljs-keyword">while</span> <span class="hljs-literal">True</span>:  <span class="hljs-comment"># 从摄像头读取图片</span><br><br>        <span class="hljs-keyword">global</span> success<br>        <span class="hljs-keyword">global</span> img  <span class="hljs-comment"># 因为要显示在可视化的控件内，所以要用全局的</span><br>        success, img = camera.read()<br><br>        <span class="hljs-comment"># 转为灰度图片</span><br>        <span class="hljs-keyword">if</span> success <span class="hljs-keyword">is</span> <span class="hljs-literal">True</span>:<br>            gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)<br>        <span class="hljs-keyword">else</span>:<br>            <span class="hljs-keyword">break</span><br><br>        <span class="hljs-comment"># 检测人脸，将每一帧摄像头记录的数据带入OpenCv中，让Classifier判断人脸</span><br>        <span class="hljs-comment"># 其中gray为要检测的灰度图像，1.3为每次图像尺寸减小的比例，5为minNeighbors</span><br>        face_detector = face_cascade<br>        faces = face_detector.detectMultiScale(gray, <span class="hljs-number">1.3</span>, <span class="hljs-number">5</span>)<br><br>        <span class="hljs-comment"># 框选人脸，for循环保证一个能检测的实时动态视频流</span><br>        <span class="hljs-keyword">for</span> (x, y, w, h) <span class="hljs-keyword">in</span> faces:<br>            <span class="hljs-comment"># xy为左上角的坐标,w为宽，h为高，用rectangle为人脸标记画框</span><br>            cv2.rectangle(img, (x, y), (x + w, y + w), (<span class="hljs-number">255</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>))<br>            <span class="hljs-comment"># 样本数加1</span><br>            sample_num += <span class="hljs-number">1</span><br>            <span class="hljs-comment"># 保存图像，把灰度图片看成二维数组来检测人脸区域，这里是保存在data缓冲文件夹内</span><br>            T = Total_face_num<br>            cv2.imwrite(<span class="hljs-string">&quot;./data/User.&quot;</span> + <span class="hljs-built_in">str</span>(T) + <span class="hljs-string">&#x27;.&#x27;</span> + <span class="hljs-built_in">str</span>(sample_num) + <span class="hljs-string">&#x27;.jpg&#x27;</span>, gray[y:y + h, x:x + w])<br><br>        pictur_num = <span class="hljs-number">30</span>  <span class="hljs-comment"># 表示摄像头拍摄取样的数量,越多效果越好，但获取以及训练的越慢</span><br><br>        cv2.waitKey(<span class="hljs-number">1</span>)<br>        <span class="hljs-keyword">if</span> sample_num &gt; pictur_num:<br>            <span class="hljs-keyword">break</span><br>        <span class="hljs-keyword">else</span>:  <span class="hljs-comment"># 控制台内输出进度条</span><br>            l = <span class="hljs-built_in">int</span>(sample_num / pictur_num * <span class="hljs-number">50</span>)<br>            r = <span class="hljs-built_in">int</span>((pictur_num - sample_num) / pictur_num * <span class="hljs-number">50</span>)<br>            <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;\r&quot;</span> + <span class="hljs-string">&quot;%&#123;:.1f&#125;&quot;</span>.<span class="hljs-built_in">format</span>(sample_num / pictur_num * <span class="hljs-number">100</span>) + <span class="hljs-string">&quot;=&quot;</span> * l + <span class="hljs-string">&quot;-&gt;&quot;</span> + <span class="hljs-string">&quot;_&quot;</span> * r, end=<span class="hljs-string">&quot;&quot;</span>)<br>            var.<span class="hljs-built_in">set</span>(<span class="hljs-string">&quot;%&#123;:.1f&#125;&quot;</span>.<span class="hljs-built_in">format</span>(sample_num / pictur_num * <span class="hljs-number">100</span>))  <span class="hljs-comment"># 控件可视化进度信息</span><br>            <span class="hljs-comment"># tk.Tk().update()</span><br>            window.update()  <span class="hljs-comment"># 刷新控件以实时显示进度</span><br><br><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">Train_new_face</span>():<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;\n正在训练&quot;</span>)<br>    <span class="hljs-comment"># cv2.destroyAllWindows()</span><br>    path = <span class="hljs-string">&#x27;data&#x27;</span><br><br>    <span class="hljs-comment"># 初始化识别的方法</span><br>    recog = cv2.face.LBPHFaceRecognizer_create()<br><br>    <span class="hljs-comment"># 调用函数并将数据喂给识别器训练</span><br>    faces, ids = get_images_and_labels(path)<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&#x27;本次用于训练的识别码为:&#x27;</span>)  <span class="hljs-comment"># 调试信息</span><br>    <span class="hljs-built_in">print</span>(ids)  <span class="hljs-comment"># 输出识别码</span><br><br>    <span class="hljs-comment"># 训练模型  #将输入的所有图片转成四维数组</span><br>    recog.train(faces, np.array(ids))<br>    <span class="hljs-comment"># 保存模型</span><br><br>    yml = <span class="hljs-built_in">str</span>(Total_face_num) + <span class="hljs-string">&quot;.yml&quot;</span><br>    rec_f = <span class="hljs-built_in">open</span>(yml, <span class="hljs-string">&quot;w+&quot;</span>)<br>    rec_f.close()<br>    recog.save(yml)<br><br>    <span class="hljs-comment"># recog.save(&#x27;aaa.yml&#x27;)</span><br><br><br><span class="hljs-comment"># 创建一个函数，用于从数据集文件夹中获取训练图片,并获取id</span><br><span class="hljs-comment"># 注意图片的命名格式为User.id.sampleNum</span><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">get_images_and_labels</span>(<span class="hljs-params">path</span>):<br>    image_paths = [os.path.join(path, f) <span class="hljs-keyword">for</span> f <span class="hljs-keyword">in</span> os.listdir(path)]<br>    <span class="hljs-comment"># 新建连个list用于存放</span><br>    face_samples = []<br>    ids = []<br><br>    <span class="hljs-comment"># 遍历图片路径，导入图片和id添加到list中</span><br>    <span class="hljs-keyword">for</span> image_path <span class="hljs-keyword">in</span> image_paths:<br><br>        <span class="hljs-comment"># 通过图片路径将其转换为灰度图片</span><br>        img = Image.<span class="hljs-built_in">open</span>(image_path).convert(<span class="hljs-string">&#x27;L&#x27;</span>)<br><br>        <span class="hljs-comment"># 将图片转化为数组</span><br>        img_np = np.array(img, <span class="hljs-string">&#x27;uint8&#x27;</span>)<br><br>        <span class="hljs-keyword">if</span> os.path.split(image_path)[-<span class="hljs-number">1</span>].split(<span class="hljs-string">&quot;.&quot;</span>)[-<span class="hljs-number">1</span>] != <span class="hljs-string">&#x27;jpg&#x27;</span>:<br>            <span class="hljs-keyword">continue</span><br><br>        <span class="hljs-comment"># 为了获取id，将图片和路径分裂并获取</span><br>        <span class="hljs-built_in">id</span> = <span class="hljs-built_in">int</span>(os.path.split(image_path)[-<span class="hljs-number">1</span>].split(<span class="hljs-string">&quot;.&quot;</span>)[<span class="hljs-number">1</span>])<br><br>        <span class="hljs-comment"># 调用熟悉的人脸分类器</span><br>        detector = cv2.CascadeClassifier(<span class="hljs-string">&#x27;haarcascade_frontalface_default.xml&#x27;</span>)<br><br>        faces = detector.detectMultiScale(img_np)<br><br>        <span class="hljs-comment"># 将获取的图片和id添加到list中</span><br>        <span class="hljs-keyword">for</span> (x, y, w, h) <span class="hljs-keyword">in</span> faces:<br>            face_samples.append(img_np[y:y + h, x:x + w])<br>            ids.append(<span class="hljs-built_in">id</span>)<br>    <span class="hljs-keyword">return</span> face_samples, ids<br><br><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">write_config</span>():<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;新人脸训练结束&quot;</span>)<br>    f = <span class="hljs-built_in">open</span>(<span class="hljs-string">&#x27;config.txt&#x27;</span>, <span class="hljs-string">&quot;a&quot;</span>)<br>    T = Total_face_num<br>    f.write(<span class="hljs-built_in">str</span>(T) + <span class="hljs-string">&quot; User&quot;</span> + <span class="hljs-built_in">str</span>(T) + <span class="hljs-string">&quot; \n&quot;</span>)<br>    f.close()<br>    id_dict[T] = <span class="hljs-string">&quot;User&quot;</span> + <span class="hljs-built_in">str</span>(T)<br><br>    <span class="hljs-comment"># 这里修改文件的方式是先读入内存，然后修改内存中的数据，最后写回文件</span><br>    f = <span class="hljs-built_in">open</span>(<span class="hljs-string">&#x27;config.txt&#x27;</span>, <span class="hljs-string">&#x27;r+&#x27;</span>)<br>    flist = f.readlines()<br>    flist[<span class="hljs-number">0</span>] = <span class="hljs-built_in">str</span>(<span class="hljs-built_in">int</span>(flist[<span class="hljs-number">0</span>]) + <span class="hljs-number">1</span>) + <span class="hljs-string">&quot; \n&quot;</span><br>    f.close()<br><br>    f = <span class="hljs-built_in">open</span>(<span class="hljs-string">&#x27;config.txt&#x27;</span>, <span class="hljs-string">&#x27;w+&#x27;</span>)<br>    f.writelines(flist)<br>    f.close()<br><br><br><span class="hljs-string">&#x27;&#x27;&#x27;</span><br><span class="hljs-string">============================================================================================</span><br><span class="hljs-string">以上是录入新人脸信息功能的实现</span><br><span class="hljs-string">============================================================================================</span><br><span class="hljs-string">&#x27;&#x27;&#x27;</span><br><br><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">scan_face</span>():<br>    <span class="hljs-comment"># 使用之前训练好的模型</span><br>    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(Total_face_num):  <span class="hljs-comment"># 每个识别器都要用</span><br>        i += <span class="hljs-number">1</span><br>        yml = <span class="hljs-built_in">str</span>(i) + <span class="hljs-string">&quot;.yml&quot;</span><br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;\n本次:&quot;</span> + yml)  <span class="hljs-comment"># 调试信息</span><br>        recognizer.read(yml)<br><br>        ave_poss = <span class="hljs-number">0</span><br>        <span class="hljs-keyword">for</span> times <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-number">10</span>):  <span class="hljs-comment"># 每个识别器扫描十遍</span><br>            times += <span class="hljs-number">1</span><br>            cur_poss = <span class="hljs-number">0</span><br>            <span class="hljs-keyword">global</span> success<br>            <span class="hljs-keyword">global</span> img<br><br>            <span class="hljs-keyword">global</span> system_state_lock<br>            <span class="hljs-keyword">while</span> system_state_lock == <span class="hljs-number">2</span>:  <span class="hljs-comment"># 如果正在录入新面孔就阻塞</span><br>                <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;\r刷脸被录入面容阻塞&quot;</span>, end=<span class="hljs-string">&quot;&quot;</span>)<br>                <span class="hljs-keyword">pass</span><br><br>            success, img = camera.read()<br>            gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)<br>            <span class="hljs-comment"># 识别人脸</span><br>            faces = face_cascade.detectMultiScale(<br>                gray,<br>                scaleFactor=<span class="hljs-number">1.2</span>,<br>                minNeighbors=<span class="hljs-number">5</span>,<br>                minSize=(<span class="hljs-built_in">int</span>(W_size), <span class="hljs-built_in">int</span>(H_size))<br>            )<br>            <span class="hljs-comment"># 进行校验</span><br>            <span class="hljs-keyword">for</span> (x, y, w, h) <span class="hljs-keyword">in</span> faces:<br><br>                <span class="hljs-comment"># global system_state_lock</span><br>                <span class="hljs-keyword">while</span> system_state_lock == <span class="hljs-number">2</span>:  <span class="hljs-comment"># 如果正在录入新面孔就阻塞</span><br>                    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;\r刷脸被录入面容阻塞&quot;</span>, end=<span class="hljs-string">&quot;&quot;</span>)<br>                    <span class="hljs-keyword">pass</span><br>                <span class="hljs-comment"># 这里调用Cv2中的rectangle函数 在人脸周围画一个矩形</span><br>                cv2.rectangle(img, (x, y), (x + w, y + h), (<span class="hljs-number">0</span>, <span class="hljs-number">255</span>, <span class="hljs-number">0</span>), <span class="hljs-number">2</span>)<br>                <span class="hljs-comment"># 调用分类器的预测函数，接收返回值标签和置信度</span><br>                idnum, confidence = recognizer.predict(gray[y:y + h, x:x + w])<br>                conf = confidence<br>                <span class="hljs-comment"># 计算出一个检验结果</span><br>                <span class="hljs-keyword">if</span> confidence &lt; <span class="hljs-number">100</span>:  <span class="hljs-comment"># 可以识别出已经训练的对象——直接输出姓名在屏幕上</span><br>                    <span class="hljs-keyword">if</span> idnum <span class="hljs-keyword">in</span> id_dict:<br>                        user_name = id_dict[idnum]<br>                    <span class="hljs-keyword">else</span>:<br>                        <span class="hljs-comment"># print(&quot;无法识别的ID:&#123;&#125;\t&quot;.format(idnum), end=&quot;&quot;)</span><br>                        user_name = <span class="hljs-string">&quot;Untagged user:&quot;</span> + <span class="hljs-built_in">str</span>(idnum)<br>                    confidence = <span class="hljs-string">&quot;&#123;0&#125;%&quot;</span>, <span class="hljs-built_in">format</span>(<span class="hljs-built_in">round</span>(<span class="hljs-number">100</span> - confidence))<br>                <span class="hljs-keyword">else</span>:  <span class="hljs-comment"># 无法识别此对象，那么就开始训练</span><br>                    user_name = <span class="hljs-string">&quot;unknown&quot;</span><br>                    <span class="hljs-comment"># print(&quot;检测到陌生人脸\n&quot;)</span><br><br>                    <span class="hljs-comment"># cv2.destroyAllWindows()</span><br>                    <span class="hljs-comment"># global Total_face_num</span><br>                    <span class="hljs-comment"># Total_face_num += 1</span><br>                    <span class="hljs-comment"># Get_new_face()  # 采集新人脸</span><br>                    <span class="hljs-comment"># Train_new_face()  # 训练采集到的新人脸</span><br>                    <span class="hljs-comment"># write_config()  # 修改配置文件</span><br>                    <span class="hljs-comment"># recognizer.read(&#x27;aaa.yml&#x27;)  # 读取新识别器</span><br><br>                <span class="hljs-comment"># 加载一个字体用于输出识别对象的信息</span><br>                font = cv2.FONT_HERSHEY_SIMPLEX<br><br>                <span class="hljs-comment"># 输出检验结果以及用户名</span><br>                cv2.putText(img, <span class="hljs-built_in">str</span>(user_name), (x + <span class="hljs-number">5</span>, y - <span class="hljs-number">5</span>), font, <span class="hljs-number">1</span>, (<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">255</span>), <span class="hljs-number">1</span>)<br>                cv2.putText(img, <span class="hljs-built_in">str</span>(confidence), (x + <span class="hljs-number">5</span>, y + h - <span class="hljs-number">5</span>), font, <span class="hljs-number">1</span>, (<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>), <span class="hljs-number">1</span>)<br><br>                <span class="hljs-comment"># 展示结果</span><br>                <span class="hljs-comment"># cv2.imshow(&#x27;camera&#x27;, img)</span><br><br>                <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;conf=&quot;</span> + <span class="hljs-built_in">str</span>(conf), end=<span class="hljs-string">&quot;\t&quot;</span>)<br>                <span class="hljs-keyword">if</span> <span class="hljs-number">15</span> &gt; conf &gt; <span class="hljs-number">0</span>:<br>                    cur_poss = <span class="hljs-number">1</span>  <span class="hljs-comment"># 表示可以识别</span><br>                <span class="hljs-keyword">elif</span> <span class="hljs-number">60</span> &gt; conf &gt; <span class="hljs-number">35</span>:<br>                    cur_poss = <span class="hljs-number">1</span>  <span class="hljs-comment"># 表示可以识别</span><br>                <span class="hljs-keyword">else</span>:<br>                    cur_poss = <span class="hljs-number">0</span>  <span class="hljs-comment"># 表示不可以识别</span><br><br>            k = cv2.waitKey(<span class="hljs-number">1</span>)<br>            <span class="hljs-keyword">if</span> k == <span class="hljs-number">27</span>:<br>                <span class="hljs-comment"># cam.release()  # 释放资源</span><br>                cv2.destroyAllWindows()<br>                <span class="hljs-keyword">break</span><br><br>            ave_poss += cur_poss<br><br>        <span class="hljs-keyword">if</span> ave_poss &gt;= <span class="hljs-number">5</span>:  <span class="hljs-comment"># 有一半以上识别说明可行则返回</span><br>            <span class="hljs-keyword">return</span> i<br><br>    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>  <span class="hljs-comment"># 全部过一遍还没识别出说明无法识别</span><br><br><br><span class="hljs-string">&#x27;&#x27;&#x27;</span><br><span class="hljs-string">============================================================================================</span><br><span class="hljs-string">以上是关于刷脸功能的设计</span><br><span class="hljs-string">============================================================================================</span><br><span class="hljs-string">&#x27;&#x27;&#x27;</span><br><br><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">f_scan_face_thread</span>():<br>    <span class="hljs-comment"># 使用之前训练好的模型</span><br>    <span class="hljs-comment"># recognizer.read(&#x27;aaa.yml&#x27;)</span><br>    var.<span class="hljs-built_in">set</span>(<span class="hljs-string">&#x27;刷脸&#x27;</span>)<br>    ans = scan_face()<br>    <span class="hljs-keyword">if</span> ans == <span class="hljs-number">0</span>:<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;最终结果：无法识别&quot;</span>)<br>        var.<span class="hljs-built_in">set</span>(<span class="hljs-string">&quot;最终结果：无法识别&quot;</span>)<br><br>    <span class="hljs-keyword">else</span>:<br>        ans_name = <span class="hljs-string">&quot;最终结果：&quot;</span> + <span class="hljs-built_in">str</span>(ans) + id_dict[ans]<br>        <span class="hljs-built_in">print</span>(ans_name)<br>        var.<span class="hljs-built_in">set</span>(ans_name)<br><br>    <span class="hljs-keyword">global</span> system_state_lock<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;锁被释放0&quot;</span>)<br>    system_state_lock = <span class="hljs-number">0</span>  <span class="hljs-comment"># 修改system_state_lock,释放资源</span><br><br><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">f_scan_face</span>():<br>    <span class="hljs-keyword">global</span> system_state_lock<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;\n当前锁的值为：&quot;</span> + <span class="hljs-built_in">str</span>(system_state_lock))<br>    <span class="hljs-keyword">if</span> system_state_lock == <span class="hljs-number">1</span>:<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;阻塞，因为正在刷脸&quot;</span>)<br>        <span class="hljs-keyword">return</span> <span class="hljs-number">0</span><br>    <span class="hljs-keyword">elif</span> system_state_lock == <span class="hljs-number">2</span>:  <span class="hljs-comment"># 如果正在录入新面孔就阻塞</span><br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;\n刷脸被录入面容阻塞\n&quot;</span><br>              <span class="hljs-string">&quot;&quot;</span>)<br>        <span class="hljs-keyword">return</span> <span class="hljs-number">0</span><br>    system_state_lock = <span class="hljs-number">1</span><br>    p = threading.Thread(target=f_scan_face_thread)<br>    p.setDaemon(<span class="hljs-literal">True</span>)  <span class="hljs-comment"># 把线程P设置为守护线程 若主线程退出 P也跟着退出</span><br>    p.start()<br><br><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">f_rec_face_thread</span>():<br>    var.<span class="hljs-built_in">set</span>(<span class="hljs-string">&#x27;录入&#x27;</span>)<br>    cv2.destroyAllWindows()<br>    <span class="hljs-keyword">global</span> Total_face_num<br>    Total_face_num += <span class="hljs-number">1</span><br>    Get_new_face()  <span class="hljs-comment"># 采集新人脸</span><br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;采集完毕，开始训练&quot;</span>)<br>    <span class="hljs-keyword">global</span> system_state_lock  <span class="hljs-comment"># 采集完就可以解开锁</span><br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;锁被释放0&quot;</span>)<br>    system_state_lock = <span class="hljs-number">0</span><br><br>    Train_new_face()  <span class="hljs-comment"># 训练采集到的新人脸</span><br>    write_config()  <span class="hljs-comment"># 修改配置文件</span><br><br><br><span class="hljs-comment">#    recognizer.read(&#x27;aaa.yml&#x27;)  # 读取新识别器</span><br><br><span class="hljs-comment"># global system_state_lock</span><br><span class="hljs-comment"># print(&quot;锁被释放0&quot;)</span><br><span class="hljs-comment"># system_state_lock = 0  # 修改system_state_lock,释放资源</span><br><br><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">f_rec_face</span>():<br>    <span class="hljs-keyword">global</span> system_state_lock<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;当前锁的值为：&quot;</span> + <span class="hljs-built_in">str</span>(system_state_lock))<br>    <span class="hljs-keyword">if</span> system_state_lock == <span class="hljs-number">2</span>:<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;阻塞，因为正在录入面容&quot;</span>)<br>        <span class="hljs-keyword">return</span> <span class="hljs-number">0</span><br>    <span class="hljs-keyword">else</span>:<br>        system_state_lock = <span class="hljs-number">2</span>  <span class="hljs-comment"># 修改system_state_lock</span><br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;改为2&quot;</span>, end=<span class="hljs-string">&quot;&quot;</span>)<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;当前锁的值为：&quot;</span> + <span class="hljs-built_in">str</span>(system_state_lock))<br><br>    p = threading.Thread(target=f_rec_face_thread)<br>    p.setDaemon(<span class="hljs-literal">True</span>)  <span class="hljs-comment"># 把线程P设置为守护线程 若主线程退出 P也跟着退出</span><br>    p.start()<br>    <span class="hljs-comment"># tk.Tk().update()</span><br><br><br><span class="hljs-comment">#  system_state_lock = 0  # 修改system_state_lock,释放资源</span><br><br><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">f_exit</span>():  <span class="hljs-comment"># 退出按钮</span><br>    exit()<br><br><br><span class="hljs-string">&#x27;&#x27;&#x27;</span><br><span class="hljs-string">============================================================================================</span><br><span class="hljs-string">以上是关于多线程的设计</span><br><span class="hljs-string">============================================================================================</span><br><span class="hljs-string">&#x27;&#x27;&#x27;</span><br><br>window = tk.Tk()<br>window.title(<span class="hljs-string">&#x27;Cheney\&#x27; Face_rec 3.0&#x27;</span>)   <span class="hljs-comment"># 窗口标题</span><br>window.geometry(<span class="hljs-string">&#x27;1000x500&#x27;</span>)  <span class="hljs-comment"># 这里的乘是小x</span><br><br><span class="hljs-comment"># 在图形界面上设定标签，类似于一个提示窗口的作用</span><br>var = tk.StringVar()<br>l = tk.Label(window, textvariable=var, bg=<span class="hljs-string">&#x27;green&#x27;</span>, fg=<span class="hljs-string">&#x27;white&#x27;</span>, font=(<span class="hljs-string">&#x27;Arial&#x27;</span>, <span class="hljs-number">12</span>), width=<span class="hljs-number">50</span>, height=<span class="hljs-number">4</span>)<br><span class="hljs-comment"># 说明： bg为背景，fg为字体颜色，font为字体，width为长，height为高，这里的长和高是字符的长和高，比如height=2,就是标签有2个字符这么高</span><br>l.pack()  <span class="hljs-comment"># 放置l控件</span><br><br><span class="hljs-comment"># 在窗口界面设置放置Button按键并绑定处理函数</span><br>button_a = tk.Button(window, text=<span class="hljs-string">&#x27;开始刷脸&#x27;</span>, font=(<span class="hljs-string">&#x27;Arial&#x27;</span>, <span class="hljs-number">12</span>), width=<span class="hljs-number">10</span>, height=<span class="hljs-number">2</span>, command=f_scan_face)<br>button_a.place(x=<span class="hljs-number">800</span>, y=<span class="hljs-number">120</span>)<br><br>button_b = tk.Button(window, text=<span class="hljs-string">&#x27;录入人脸&#x27;</span>, font=(<span class="hljs-string">&#x27;Arial&#x27;</span>, <span class="hljs-number">12</span>), width=<span class="hljs-number">10</span>, height=<span class="hljs-number">2</span>, command=f_rec_face)<br>button_b.place(x=<span class="hljs-number">800</span>, y=<span class="hljs-number">220</span>)<br><br>button_b = tk.Button(window, text=<span class="hljs-string">&#x27;退出&#x27;</span>, font=(<span class="hljs-string">&#x27;Arial&#x27;</span>, <span class="hljs-number">12</span>), width=<span class="hljs-number">10</span>, height=<span class="hljs-number">2</span>, command=f_exit)<br>button_b.place(x=<span class="hljs-number">800</span>, y=<span class="hljs-number">320</span>)<br><br>panel = tk.Label(window, width=<span class="hljs-number">500</span>, height=<span class="hljs-number">350</span>)  <span class="hljs-comment"># 摄像头模块大小</span><br>panel.place(x=<span class="hljs-number">10</span>, y=<span class="hljs-number">100</span>)  <span class="hljs-comment"># 摄像头模块的位置</span><br>window.config(cursor=<span class="hljs-string">&quot;arrow&quot;</span>)<br><br><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">video_loop</span>():  <span class="hljs-comment"># 用于在label内动态展示摄像头内容（摄像头嵌入控件）</span><br>    <span class="hljs-comment"># success, img = camera.read()  # 从摄像头读取照片</span><br>    <span class="hljs-keyword">global</span> success<br>    <span class="hljs-keyword">global</span> img<br>    <span class="hljs-keyword">if</span> success:<br>        cv2.waitKey(<span class="hljs-number">1</span>)<br>        cv2image = cv2.cvtColor(img, cv2.COLOR_BGR2RGBA)  <span class="hljs-comment"># 转换颜色从BGR到RGBA</span><br>        current_image = Image.fromarray(cv2image)  <span class="hljs-comment"># 将图像转换成Image对象</span><br>        imgtk = ImageTk.PhotoImage(image=current_image)<br>        panel.imgtk = imgtk<br>        panel.config(image=imgtk)<br>        window.after(<span class="hljs-number">1</span>, video_loop)<br><br><br>video_loop()<br><br><span class="hljs-comment">#  窗口循环，用于显示</span><br>window.mainloop()<br><br><span class="hljs-string">&#x27;&#x27;&#x27;</span><br><span class="hljs-string">============================================================================================</span><br><span class="hljs-string">以上是关于界面的设计</span><br><span class="hljs-string">============================================================================================</span><br><span class="hljs-string">&#x27;&#x27;&#x27;</span><br><br></code></pre></td></tr></table></figure>




            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/">人工智能</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/Python/">Python</a>
                    
                      <a class="hover-with-bg" href="/tags/OpenCv/">OpenCv</a>
                    
                      <a class="hover-with-bg" href="/tags/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0/">深度学习</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2021/10/01/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD__%E6%96%91%E9%A9%AC%E9%97%AE%E9%A2%98%E5%A4%9A%E6%96%B9%E6%B3%95%E6%B1%82%E8%A7%A3/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">斑马问题多方法求解</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2021/06/06/%E6%95%B0%E6%8D%AE%E5%BA%93__%E5%A4%96%E5%8D%96%E6%95%B0%E6%8D%AE%E5%BA%93%E7%AE%A1%E7%90%86%E7%B3%BB%E7%BB%9F/">
                        <span class="hidden-mobile">外卖数据库管理系统</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://cheney822.gitee.io/" target="_blank" rel="nofollow noopener"><span>备用网址</span></a> 
  </div>
  

  
  <!-- 备案信息 -->
  <div class="beian">
    <span>
      <a href="http://beian.miit.gov.cn/" target="_blank" rel="nofollow noopener">
        皖ICP备2022002876号-1
      </a>
    </span>
    
  </div>


  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/js/local-search.js" ></script>



  
    <script  src="/js/img-lazyload.js" ></script>
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  






  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
        typing(title);
      
    })(window, document);
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>


</body>
</html>
